import { markRaw } from "vue";
import { RouteRecordRaw } from "vue-router";
const moduleFile = require.context("@/views", true, /.vue$/);
// 异步路由处理（工程化获取映射组件）
export const addAsyncRouteEngineering = (asyncRoutes: Array<RouteRecordRaw>) => {
  // 获取 views文件夹下的文件目录
  const moduleFileKyes = moduleFile.keys();
  asyncRoutes.forEach((route: RouteRecordRaw) => {
    // 微应用路由 统一处理
    if (route.meta?.microApp) {
      if (!route.redirect) {
        route.meta.keepAlive = (route as any).webCache;
        route.component = () => import("@/layout/components/microAppView.vue");
      }
    } else {
      if (!route.redirect) {
        // 非微应用路由
        (route.meta as any).keepAlive = (route as any).webCache;
        const compIndex = moduleFileKyes.findIndex(md => {
          if (md.includes("index.vue")) {
            const targetPath = formatFilePathtoRoutePath(md);
            return targetPath === route.path;
          }
          return false;
        });
        let component;
        if (compIndex > -1) {
          component = moduleFile(moduleFileKyes[compIndex]).default;
        } else {
          component = () => import("@/views/404.vue");
        }
        route.component = markRaw(component);
      }
    }
    // 如果有子路由那么递归处理
    if (route.children && route.children.length) return addAsyncRouteEngineering(route.children);
  });
  return asyncRoutes;
};
export const formatFilePathtoRoutePath = (str: string) => {
  if (typeof str !== "string") {
    return "";
  }
  const reg = /^(.){1}|(\/index.vue){1}$/g;
  return str.replace(reg, "");
};
